const React = require('react');
const {
  View,
  StyleSheet,
} = require('react-native');
const {
  JDDevice,
  JDTouchable,
  JDImage,
  JDViewPager,
  JDText
} = require('@areslabs/jdreact-core-lib');

const BANNERS = [
  {
    "bannerId": 4686,
    "imgUrl": "https://img30.360buyimg.com/njmobilecms/jfs/t3187/78/2902161405/46549/af9d93d1/57e7dea2N384f1a2f.jpg",
    "linkUrl": "https://sale.jd.com/m/act/cvJgdk3mbf7.html",
  },
  {
    "bannerId": 4694,
    "imgUrl": "https://img30.360buyimg.com/njmobilecms/jfs/t3142/277/2531782606/27298/32f7ec49/57e346ebN5082df8d.jpg",
    "linkUrl": "https://1.m.jd.com/detail/next?itemId=1300000000000119106",
  }
];

class CustomIndicatorViewPager extends React.Component {
  static defaultProps = function() {
    let dataSource = new JDViewPager.DataSource({
      pageHasChanged: (p1, p2) => p1 !== p2,
    });
    return {
      dataSource: dataSource.cloneWithPages(BANNERS)
    };
  }();

  render() {
    return (
      <View style={styles.xx}>
        <JDText>自定制指示点的ViewPager</JDText>
        <JDViewPager
          style={styles.viewPager}
          dataSource={this.props.dataSource}
          renderPage={this._renderPage}
          isLoop={true}
          autoPlay={true}
          renderPageIndicator={() => (<PageIndicator />)}
        />
      </View>
    );
  }

  _renderPage = (data) => {
    return (
      <JDTouchable style={styles.bannerItem}>
        <JDImage style={styles.bannerImage} source={{uri: data.imgUrl}} />
      </JDTouchable>
    );
  };
}

class PageIndicator extends React.Component {
  render() {
    return (
      <View style={styles.indicator}>
        {this._renderDots()}
      </View>
    )
  }

  _renderDots = () => {
    let dots = [];
    let activePage = this.props.activePage;
    for(let i = 0; i < this.props.pageCount; i++) {
      dots.push(
        <View style={[styles.dot, activePage === i && styles.activeDot]} key={`dot-${i}`} />
      );
    }
    return dots;
  };
}

const BANNER_HEIGHT = JDDevice.width * 200 / 640;
const styles = StyleSheet.create({
  viewPager: {
    width: JDDevice.width,
    height: BANNER_HEIGHT,
    overflow: 'hidden',
    marginBottom: JDDevice.getRpx(40),
  },
  bannerItem: {
    flex: 1
  },
  bannerImage: {
    width: JDDevice.width,
    height: BANNER_HEIGHT,
    resizeMode: 'stretch',
  },

  indicator: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    position: 'absolute',
    top: 10,
    right: 0,
    left: 0,
  },
  dot: {
    width: 6,
    height: 6,
    borderRadius: 3,
    backgroundColor: 'rgba(100,100,100,0.5)',
    margin: 5,
  },
  activeDot: {
    backgroundColor: '#FFF',
  }

});

module.exports = CustomIndicatorViewPager;
